/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef __SGCONF_H__
#define __SGCONF_H__

#include <string>

#include <boost/asio.hpp>
#include <boost/scoped_array.hpp>

#include <openssl/blowfish.h>

#include "proto.h"

using namespace boost::asio;

class SGCONF {
    public:
        SGCONF();
        SGCONF(const std::string & h,
               const std::string & p,
               const std::string & l,
               const std::string & pwd);
        ~SGCONF();

        void SetHost(const std::string & h) { host = h; };
        void SetPort(const std::string & p) { port = p; };
        void SetLogin(const std::string & l) { login = l; };
        void SetPassword(const std::string & p)
        {
            password = p;
            BF_set_key(&key, password.length(),
                       reinterpret_cast<const unsigned char *>(password.c_str()));
        };

        bool Perform(const std::string & xml);

        const std::string & GetResult() const { return xml; };

    private:
        boost::asio::io_service io_service;
        deadline_timer timer;
        ip::tcp::socket socket;

        std::string host;
        std::string port;
        std::string login;
        std::string password;

        mutable boost::scoped_array<unsigned char> iv;
        BF_KEY key;

        struct RESP::HEADER respHeader;
        struct RESP::CRYPTO_HEADER respCryptoHeader;
        unsigned char cryptoRespBuffer[sizeof(respCryptoHeader)];
        boost::scoped_array<unsigned char> cryptoXMLBlock;
        boost::scoped_array<unsigned char> XMLBlock;
        size_t dataSize;
        size_t dataReceived;
        std::string xml;

        bool Connect();

        void HandleHeader(const boost::system::error_code & error, size_t received);
        void HandleCryptoHeader(const boost::system::error_code & error, size_t received);
        void HandleHeadersTimeout(const boost::system::error_code & error);
        void HandleXML(const boost::system::error_code & error, size_t received);
        void HandleXMLTimeout(const boost::system::error_code & error);

};

#endif
